#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : #time#
# @Author  : Tuut
# @Email   : 49616026@qq.com
# @File    : #handleName#.py

##
# #handle_desp_1#
# #handle_desp_2#
#
from bottle import Bottle, request, response

from cms.bean.#beanName# import #beanName#
from conn.MyPagerFactory import MyPager
from conn.MyLogs import MyLogs

#routeViewName# = Bottle()


@#routeViewName#.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@#routeViewName#.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


# CMS Web业务
# Vue+ele展示界面数据接口
class #handleName#:
    impl = None
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }

    def __init__(self, service):
        #handleName#.impl = service
        return

    # -- index
    @staticmethod
    @#routeViewName#.get('/')
    def index():
        return {'code': 200, 'data': '', 'message': '#handle_desp_1#'}

    # -- 数据标准分页查询
    @staticmethod
    @#routeViewName#.get('/fetch')
    def #method_fetch_name#():
        try:
            params = {"psno": request.params.catalogPsno,
                      "key": str(request.params.key).replace(" ", ""),
                      "pageSize": request.params.pageSize,
                      "pageNum": request.params.pageNum}
            res = #handleName#.impl.fetch_with_param(params)
            _pages = MyPager.make_pager(id=str("table_#beanName#").lower(),
                                        res=res['data'],
                                        page_size=int(params['pageSize']),
                                        data_total=res['total'],
                                        single_pager=False)
            return {'code': 200, 'data': {'list': _pages["lists"],
                                          'total': _pages["total"],
                                          'pageSize': _pages["pageSize"],
                                          'pages': _pages["pages"]}, 'message': ''}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': {}, 'message': #handleName#.ERROR_CODE["80"]}

    # -- 数据标准分页查询
    @staticmethod
    @#routeViewName#.get('/info')
    def #method_info_name#():
        try:
            id = request.params.id
            res = #handleName#.impl.info(input_id=id)
            return {'code': 200, 'data': res['data'], 'message': ''}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': {}, 'message': #handleName#.ERROR_CODE["80"]}

    # -- 数据编辑添加
    @staticmethod
    @#routeViewName#.post('/add')
    def #method_add_name#():
        try:
            if request.json is not None:
                _cls = #beanName#
                _cls.my#beanName#()
                res = #handleName#.impl.add(_cls)
                if res['code'] == 200:
                    return {'code': 200, 'data': None, 'message': ''}
                else:
                    return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["102"]}
            else:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["100"]}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': {}, 'message': #handleName#.ERROR_CODE["80"]}

    # -- 数据编辑添加
    @staticmethod
    @#routeViewName#.put('/update')
    def #method_modify_name#():
        try:
            if request.json is not None:
                _obj = #beanName#()
                id = request.json['id']
                res = #handleName#.impl.update(input_id=id, data=_obj)
                if res['code'] == 200:
                    return {'code': 200, 'data': None, 'message': ''}
                else:
                    return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["102"]}
            else:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["80"]}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': {}, 'message': #handleName#.ERROR_CODE["80"]}

    # -- 数据删除
    @staticmethod
    @#routeViewName#.delete('/delete')
    def #method_delete_name#():
        try:
            id = request.params.id
            if id == 0 or len(str(id)) == 0:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["80"]}

            res = #handleName#.impl.info(input_id=id)
            if res['code'] == 500:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["109"]}

            res = #handleName#.impl.delete(input_id=id)
            if res['code'] == 200:
                return {'code': 200, 'data': None, 'message': ''}
            else:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["103"]}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': {}, 'message': #handleName#.ERROR_CODE["80"]}

    # -- 数据激活或关闭
    @staticmethod
    @#routeViewName#.put('/act')
    def #method_act_name#():
        try:
            id = 0
            if request.json is not None:
                id = request.json['id']
                view_flg = request.json['view']
            if id == 0 or len(str(id)) == 0:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["80"]}
            res = #handleName#.impl.setView(input_id=id, act_flg=view_flg)
            if res['code'] == 200:
                return {'code': 200, 'data': None, 'message': ''}
            else:
                return {'code': 500, 'data': None, 'message': #handleName#.ERROR_CODE["106"]}
        except Exception as e:
            MyLogs.logger.error(e)
            return {'code': 500, 'data': {}, 'message': #handleName#.ERROR_CODE["80"]}